angular.module('moti.controllers.regionsdetail', ['moti.services.regionsService', 'moti.services.spotsService', 'directiveModule', 'moti.directive.modal'])
    .controller('regionsDetailCtrl', ['$scope', '$location', '$routeParams', 'RegionsInterface', 'SpotsInterface', '$modal', function($scope, $location, $routeParams, RegionsInterface, SpotsInterface, $modal){

        //获取单个景区
        RegionsInterface.getRegion($routeParams.regionId).then(function(data){
            if(data != null){
                $.each(data, function(i, n){
                    (n === null || (n === "" && !$.isArray(n))) && (data[i] = "暂无");
                });
            }
            if(data.cover_image == "暂无"){
                $(".img-content").html("暂无");
            }
            data.region_type_desc = data.region_type == 0 ? "普通" : "散拼";
            $scope.regions = data;
            $(".region-content").html($scope.regions.content);
            $scope.regions.spots.length == 0 && $(".todo-list").html("该景区暂时没有景点");
        });

        //收藏按钮事件
        $scope.regionHot = function(region){
            RegionsInterface.putRegion(region.region_id, {"is_hot" : !region.is_hot}).then(function(data){
                region.is_hot = !region.is_hot;
            });
        };

        //隐藏按钮事件
        $scope.spotHidden = function(spot){
            SpotsInterface.putSpot($scope.regions.region_id, spot.spot_id, {"is_hidden" : !spot.is_hidden}).then(function(data){
                spot.is_hidden = !spot.is_hidden;
            });
        };

        //删除景区
        var dalete_modal = $modal({
            id : 'delete-modal',
            text : '确认要删除此景区吗？该操作不可恢复！'
        });
        $scope.deleteRegion = function(){
            dalete_modal.show();
        };
        $("#delete-btn").off("click").on("click", function(){
            RegionsInterface.deleteRegion($scope.regions.region_id).then(function(data){
                dalete_modal.hide();
                $modal({id : 'tip-modal', text : "删除景区成功"}).show().autoHide();
                $location.path('/regionsList');
            });
        });

        //景点排序
        $scope.spotSort = {
            onSort: function(evt){
                var update_pos;
                if(evt.newIndex == 0){
                    update_pos = evt.models[evt.newIndex + 1].pos - 65535;
                }else if(evt.newIndex == $scope.regions.spots.length - 1){
                    update_pos = evt.models[evt.newIndex - 1].pos + 65535;
                }else{
                    update_pos = (evt.models[evt.newIndex - 1].pos + evt.models[evt.newIndex + 1].pos) / 2;
                }
                SpotsInterface.putSpot(evt.model.region_id, evt.model.spot_id, {"pos" : update_pos});
            }
        };

    }]);